package com.opennews.openplatform.familyexpenseapi.jooq

import com.opennews.openplatform.myspringbootcore.util.DateHelper
import org.jooq.Field
import org.jooq.Record
import java.time.LocalDateTime
import java.util.*

object RecordHelper {
    fun setCommonFields(record: Record) {
        setIdValue(record)
        setCreatedAtValue(record)
        setUpdatedAtValue(record)
    }

    fun setUpdateFields(record: Record) {
        setUpdatedAtValue(record)
    }

    private fun setIdValue(record: Record) {
        val field: Field<String>? = record.field("id", String::class.java)

        // Normally most of developers use UUID string with hyphens like 97ce608e-e454-4587-a60e-aad03b348145.
        // Remember to keep the hyphens when you are working on new projects.
        field?.let { record[it] = UUID.randomUUID().toString().replace("-", "") }
    }

    private fun setCreatedAtValue(record: Record) {
        val field: Field<LocalDateTime>? = record.field("date_created", LocalDateTime::class.java)
        field?.let { record[it] = DateHelper.getCurrentLocalDateTime() }
    }

    private fun setUpdatedAtValue(record: Record) {
        val field: Field<LocalDateTime>? = record.field("last_updated", LocalDateTime::class.java)
        field?.let { record[it] = DateHelper.getCurrentLocalDateTime() }
    }
}